package com.tedu.ds.employee.controller;

import com.tedu.ds.base.response.JsonResult;
import com.tedu.ds.employee.mapper.EmployeeMapper;
import com.tedu.ds.employee.pojo.dto.EmployeeLoginParam;
import com.tedu.ds.employee.pojo.dto.EmployeeQuery;
import com.tedu.ds.employee.pojo.dto.EmployeeSaveParam;
import com.tedu.ds.employee.pojo.entity.Employee;
import com.tedu.ds.employee.pojo.vo.EmployeeVO;
import com.tedu.ds.employee.service.EmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("/v1/employee")
@Api(tags = "员工管理模块")
@Slf4j
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @PostMapping("save")
    @ApiOperation("新增和更新功能")
    public JsonResult save(@RequestBody EmployeeSaveParam employeeSaveParam){
        employeeService.save(employeeSaveParam);
        return JsonResult.ok();
    }
    @PostMapping("delete/{id}")
    @ApiOperation("删除功能")
    @ApiImplicitParam(name = "id", value = "员工id", required = true)
    public JsonResult deleteById(@PathVariable Long id){
        employeeService.deleteById(id);
        return JsonResult.ok();
    }
    @PostMapping("login")
    @ApiOperation("登录功能")
    public JsonResult login(@RequestBody EmployeeLoginParam employeeLoginParam, @ApiIgnore HttpSession session){
        EmployeeVO employeeVO = employeeService.login(employeeLoginParam);
        session.setAttribute("employeeVO", employeeVO);
        return JsonResult.ok();
    }
    @GetMapping("logout")
    @ApiOperation("退出功能")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("employeeVO");
        session.invalidate();
        return JsonResult.ok();
    }
    @GetMapping("currentEmployee")
    @ApiOperation("获取当前登录员工状态")
    public JsonResult currentEmployee(@ApiIgnore HttpSession session){
        EmployeeVO employeeVO = (EmployeeVO) session.getAttribute("employeeVO");
        return JsonResult.ok(employeeVO);
    }
    @PostMapping("select")
    @ApiOperation("查询功能")
    public JsonResult select(@RequestBody EmployeeQuery employeeQuery){
        List<EmployeeVO> list =employeeService.select(employeeQuery);
        return JsonResult.ok(list);
    }

    @GetMapping("/select/{username}")
    @ApiOperation("根据员工名查询员工信息")
    public JsonResult selectByUsername(@PathVariable String username){
        return JsonResult.ok(employeeService.selectByUsername(username));
    }

    @PostMapping("/import")
    public String importEmployeeData(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "文件为空";
        }

        try {
            // 解析 Excel 文件并获取员工数据
            List<Employee> employees = parseExcel(file);
            // 将员工数据保存到数据库
            int time = 1;
            for (Employee e : employees) {
                employeeMapper.insert(e);
                log.info("第{}次新增到数据库，新增成功", time++);
            }
            return "导入成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "导入失败: " + e.getMessage();
        }
    }

    /**
     * 解析 Excel 文件并提取员工数据
     *
     * @param file 上传的 Excel 文件
     * @return 返回解析后的员工列表
     * @throws IOException 如果解析过程中发生 IO 错误
     */
    private List<Employee> parseExcel(MultipartFile file) throws IOException {
        // Step 1: 将 MultipartFile 转换为 byte[]
        byte[] bytes = file.getBytes();

        // Step 2: 创建 ByteArrayInputStream，确保输入流可以重置
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);

        Workbook workbook = null;
        try {
            // Step 3: 尝试创建 XSSFWorkbook (适用于 .xlsx 文件)
            try {
                workbook = new XSSFWorkbook(bis);
            } catch (Exception e) {
                // 如果失败，则尝试创建 HSSFWorkbook (适用于 .xls 文件)
                bis.reset(); // 重置输入流
                workbook = new HSSFWorkbook(bis);
            }

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            // 获取行迭代器
            Iterator<Row> rowIterator = sheet.iterator();

            List<Employee> employees = new ArrayList<>();
            boolean isFirstRow = true;

            // 遍历每一行
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();

                // 跳过标题行
                if (isFirstRow) {
                    isFirstRow = false;
                    continue;
                }

                // 创建一个新的员工对象
                Employee employee = new Employee();

                // 设置员工的各个属性
                try {
                    // 使用辅助方法获取每个单元格的值
                    employee.setRealName(getCellValueAsString(row.getCell(0)));
                    employee.setUsername(getCellValueAsString(row.getCell(1)));
                    employee.setPassword(getCellValueAsString(row.getCell(2)));

                    if (row.getCell(3) != null) {
                        employee.setEmail(getCellValueAsString(row.getCell(3)));
                    }

                    if (row.getCell(4) != null) {
                        employee.setPhone(getCellValueAsString(row.getCell(4)));
                    }

                    if (row.getCell(5) != null && row.getCell(5).getCellType() == CellType.NUMERIC) {
                        employee.setAge((int) row.getCell(5).getNumericCellValue());
                    }

                    if (row.getCell(6) != null && row.getCell(6).getCellType() == CellType.NUMERIC) {
                        employee.setGender(String.valueOf((int) row.getCell(6).getNumericCellValue()));
                    }

                    if (row.getCell(7) != null && row.getCell(7).getCellType() == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(row.getCell(7))) {
                            employee.setCreateTime(row.getCell(7).getDateCellValue());
                        } else {
                            log.warn("第 {} 行的创建时间不是日期格式", row.getRowNum());
                        }
                    }

                    if (row.getCell(8) != null && row.getCell(8).getCellType() == CellType.NUMERIC) {
                        if (DateUtil.isCellDateFormatted(row.getCell(8))) {
                            employee.setUpdateTime(row.getCell(8).getDateCellValue());
                        } else {
                            log.warn("第 {} 行的更新时间不是日期格式", row.getRowNum());
                        }
                    }

                    if (row.getCell(9) != null && row.getCell(9).getCellType() == CellType.NUMERIC) {
                        employee.setStatus(String.valueOf((int) row.getCell(9).getNumericCellValue()));
                    }

                    if (row.getCell(10) != null && row.getCell(10).getCellType() == CellType.NUMERIC) {
                        employee.setLevel(String.valueOf((int) row.getCell(10).getNumericCellValue()));
                    }

                    if (row.getCell(11) != null && row.getCell(11).getCellType() == CellType.NUMERIC) {
                        employee.setParentId((long) row.getCell(11).getNumericCellValue());
                    }

                    if (row.getCell(12) != null && row.getCell(12).getCellType() == CellType.NUMERIC) {
                        employee.setRoleId((int) row.getCell(12).getNumericCellValue());
                    }

                    if (row.getCell(13) != null) {
                        employee.setAddress(getCellValueAsString(row.getCell(13)));
                    }

                    if (row.getCell(14) != null && row.getCell(14).getCellType() == CellType.NUMERIC) {
                        employee.setDeptId((int) row.getCell(14).getNumericCellValue());
                    }

                    // 将员工对象添加到列表中
                    employees.add(employee);

                } catch (Exception e) {
                    // 如果某一行解析失败，记录错误信息并继续处理下一行
                    log.error("解析第 {} 行时出错: {}", row.getRowNum(), e.getMessage());
                }
            }

            return employees;

        } finally {
            if (workbook != null) {
                workbook.close();
            }
            bis.close();
        }
    }

    // 辅助方法：根据单元格类型获取字符串值
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                try {
                    return cell.getCellFormula();
                } catch (IllegalStateException e) {
                    // 如果公式无法解析，尝试获取计算结果
                    return String.valueOf(cell.getNumericCellValue());
                }
            default:
                return "";
        }
    }
}
